package db;

import java.io.*;


public class Writein {
    public static void main(String[] args) throws IOException {
        RandomAccessFile raf = new RandomAccessFile("abcd", "rw");
        int insertPosition = 12;
        String content = "*#*";
        String fileName = "abcd";
        fileRandInsert(fileName, insertPosition, content);

    }

    private static void fileRandInsert(String fileName, int insertPosition, String scontent) throws IOException {
        File file = new File(fileName);
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        File tmp = File.createTempFile("hahah", ".tmp");
        FileOutputStream fos = new FileOutputStream(tmp);
        FileInputStream fis = new FileInputStream(tmp);
        raf.seek(insertPosition);
        int len = -1;
        byte[] buf = new byte[2];
        while ((len = raf.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fos.flush();
        raf.seek(insertPosition);
        byte[] bytes = scontent.getBytes();
        raf.write(bytes);
        raf.seek(insertPosition + bytes.length);
        while ((len = fis.read(buf)) != -1) {
            raf.write(buf, 0, len);
        }
        fis.close();
        fos.close();
        raf.close();
        if (fis != null) {
            fis.close();
            System.out.println("fis");
        }
        if (fos != null) {
            fos.close();
            System.out.println("fis");
        }
        if (raf != null) {
            raf.close();
            System.out.println("fis");
        }
    }

}
